---
import DefaultHead from "@astrojs/starlight/components/Head.astro";
import { Schema } from "astro-seo-schema";

import type { BreadcrumbList, ListItem, Organization, TechArticle, WithContext } from "schema-dts";

interface StarlightRouteData {
  title?: string;
  description?: string;
}

// TODO(nestor): look into inferring types from `Astro.locals.starlightRoute``
const { title, description }: StarlightRouteData = Astro.locals.starlightRoute.entry.data;

const organizationSchema: WithContext<Organization> = {
  "@context": "https://schema.org",
  "@type": "Organization",
  name: "Alchemy",
  url: Astro.url.origin,
  logo: `${Astro.url.origin}/alchemy-logo-dark.svg`,
  sameAs: [
    "https://github.com/alchemy-run/alchemy",
    "https://x.com/alchemy_run",
    "https://discord.gg/jwKw8dBJdN",
  ],
};

const ogImageUrl = `${Astro.url.origin}/og${Astro.url.pathname.endsWith("/") ? (Astro.url.pathname.slice(0, -1) || "/index") : Astro.url.pathname}.png`;

const articleSchema: WithContext<TechArticle> = {
  "@context": "https://schema.org",
  "@type": "TechArticle",
  headline: title,
  description: description || title,
  url: Astro.url.href,
  author: organizationSchema,
  publisher: organizationSchema,
  image: {
    "@type": "ImageObject",
    url: ogImageUrl,
  },
};

const pathSegments = Astro.url.pathname
  .split("/")
  .filter(s => s)

const breadcrumbSchema: WithContext<BreadcrumbList> = {
  "@context": "https://schema.org",
  "@type": "BreadcrumbList",
  itemListElement: [
    {
      "@type": "ListItem",
      position: 1,
      name: "Home",
      item: Astro.url.origin,
    },
    ...pathSegments.map((segment, i): ListItem => ({
      "@type": "ListItem",
      position: i + 2,
      name: segment.replace(/-/g, " ").replace(/\b\w/g, l => l.toUpperCase()),
      ...(i === pathSegments.length - 1 ? {} : { item: `${Astro.url.origin}/${pathSegments.slice(0, i + 1).join("/")}` }),
    })),
  ],
};
---

<DefaultHead {...Astro.props} />

<Schema item={organizationSchema}/>
{title && <Schema item={articleSchema}/>}
{pathSegments.length > 0 && <Schema item={breadcrumbSchema}/>}
